using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BCWResourceManager : MonoBehaviour
{
	public const string MESH_PATH = "MeshDB/";

	public static BCWResourceManager instance;

	public Dictionary<string, MeshResource> MeshDB = new Dictionary<string, MeshResource>();

	public Stack<TextureChanger> textureChangerStack = new Stack<TextureChanger>();

	public ResourceQueue<string> unloadQueue = new ResourceQueue<string>();

	private void Awake()
	{
		instance = this;
		MeshDB.Clear();
		StartCoroutine(MeshUnloader());
	}

	private void OnDestroy()
	{
		instance = null;
	}

	private IEnumerator MeshUnloader()
	{
		while (true)
		{
			if (unloadQueue.Count > 0)
			{
				string tempName = unloadQueue.Dequeue();
				if (MeshDB[tempName].mesh != null)
				{
					Resources.UnloadAsset(MeshDB[tempName].mesh);
					MeshDB[tempName].mesh = null;
				}
			}
			yield return null;
		}
	}

	public IEnumerator MeshLoader(TextureChanger textureChanger)
	{
		if (textureChanger != null && !string.IsNullOrEmpty(textureChanger.meshNameFromDB))
		{
			if (!MeshDB.ContainsKey(textureChanger.meshNameFromDB))
			{
				MeshDB.Add(textureChanger.meshNameFromDB, new MeshResource(textureChanger.meshNameFromDB, textureChanger.alwaysLoaded));
			}
			MeshDB[textureChanger.meshNameFromDB].CountReferences++;
			textureChanger.refCountIncreased = true;
			if (MeshDB[textureChanger.meshNameFromDB].mesh == null)
			{
				ResourceRequest meshRequest = Resources.LoadAsync("MeshDB/" + textureChanger.meshNameFromDB);
				yield return meshRequest;
				MeshDB[textureChanger.meshNameFromDB].mesh = meshRequest.asset as Mesh;
			}
			textureChanger.GetCompForTextChan();
			if (textureChanger._meshFilter != null)
			{
				textureChanger._meshFilter.sharedMesh = MeshDB[textureChanger.meshNameFromDB].mesh;
			}
			if (textureChanger.cachedMeshRenderer != null)
			{
				textureChanger.cachedMeshRenderer.enabled = true;
			}
			if (textureChanger.meshCollider != null)
			{
				textureChanger.meshCollider.sharedMesh = MeshDB[textureChanger.meshNameFromDB].mesh;
			}
		}
		yield return null;
	}

	public void UnloadMesh(string name)
	{
		if (MeshDB.ContainsKey(name))
		{
			MeshDB[name].CountReferences--;
		}
	}
}
